import 'dart:async';
import 'dart:math';
import 'package:flutter/material.dart';
import 'package:flutter_card_swiper/flutter_card_swiper.dart';
import 'package:get/get.dart';
import 'package:meco/common/index.dart';

class HomeController extends GetxController
    implements
        CeramicInteractionObserver,
        OfficialContentDeleteObserver,
        CeramicDeleteObserver {
  HomeController();

  // 陶瓷作品列表
  final RxList<Ceramic> ceramics = <Ceramic>[].obs;

  // 使用烧制计时的用户数据
  final RxList<Map<String, dynamic>> timerUsers = <Map<String, dynamic>>[].obs;

  // 官方内容列表
  final RxList<OfficialContent> officialContents = <OfficialContent>[].obs;

  // 用户信息缓存
  final Map<int, User> userCache = {};

  // 图片缓存标志
  final RxBool imagesPreloaded = false.obs;

  // 卡片滑动控制
  final RxBool isCardSwiping = false.obs;
  final RxDouble cardSwipeProgress = 0.0.obs;

  // 卡片滑动控制器
  CardSwiperController cardSwiperController = CardSwiperController();

  // 自动滑动控制
  Timer? _autoSwipeTimer;
  final RxBool isAutoSwiping = true.obs; // 默认开启自动滑动

  // 当前页面索引
  final RxInt currentIndex = 0.obs;

  // 页面控制器
  late PageController pageController;

  // 仓库
  final CeramicRepository _ceramicRepository = CeramicRepository();
  final UserRepository _userRepository = UserRepository();
  final CeramicStageRepository _ceramicStageRepository =
      CeramicStageRepository();
  final OfficialContentRepository _officialContentRepository =
      OfficialContentRepository();
  final CeramicInteractionRepository _interactionRepository =
      CeramicInteractionRepository();
  final UserFollowRepository _userFollowRepository = UserFollowRepository();

  // 当前卡片的状态
  final RxBool isCurrentCeramicLiked = false.obs;
  final RxBool isCurrentCeramicFavorited = false.obs;
  final RxBool isCurrentUserFollowed = false.obs;

  _initData() async {
    await loadCeramics();
    await loadTimerUsers();
    await loadOfficialContents();
    await preloadUserImages();
    update(["home"]);
  }

  // 加载陶瓷作品数据
  Future<void> loadCeramics() async {
    try {
      // 从数据库加载所有陶瓷作品
      final ceramicList = await _ceramicRepository.getAllCeramics();
      ceramics.value = ceramicList;

      // 预加载用户数据
      for (var ceramic in ceramicList) {
        if (!userCache.containsKey(ceramic.userId)) {
          final user = await _userRepository.getUserById(ceramic.userId);
          if (user != null) {
            userCache[ceramic.userId] = user;
          }
        }
      }
    } catch (e) {
      print('加载陶瓷数据失败: $e');
    }
  }

  // 加载使用烧制计时的用户数据
  Future<void> loadTimerUsers() async {
    try {
      // 从数据库查询所有使用烧制计时的用户数据（不做数量限制）
      final List<Map<String, dynamic>> rawResults =
          await _ceramicStageRepository.getAllTimerUsage();

      if (rawResults.isEmpty) {
        timerUsers.value = [];
        return;
      }

      // 用于去重的集合，以用户ID为键
      final Map<int, Map<String, dynamic>> uniqueUserMap = {};

      // 处理查询结果
      for (var rawData in rawResults) {
        try {
          final now = DateTime.now();

          // 获取用户ID
          final int userId = rawData['user_id'];

          // 如果这个用户已经在Map中，则跳过
          if (uniqueUserMap.containsKey(userId)) {
            continue;
          }

          // 构建User对象
          final user = User(
            id: userId,
            username: rawData['username'],
            nickname: rawData['nickname'],
            avatar: rawData['avatar'],
            createdAt:
                rawData['u_created_at'] != null
                    ? DateTime.fromMillisecondsSinceEpoch(
                      rawData['u_created_at'],
                    )
                    : now,
            updatedAt:
                rawData['u_updated_at'] != null
                    ? DateTime.fromMillisecondsSinceEpoch(
                      rawData['u_updated_at'],
                    )
                    : now,
          );

          // 构建Ceramic对象
          final ceramic = Ceramic(
            id: rawData['ceramic_id'],
            userId: userId,
            title: rawData['title'],
            description: rawData['description'],
            imageUrl: rawData['image_url'],
            isSkipped: rawData['is_skipped'] == 1,
            likeCount: rawData['like_count'] ?? 0,
            favoriteCount: rawData['favorite_count'] ?? 0,
            createdAt:
                rawData['c_created_at'] != null
                    ? DateTime.fromMillisecondsSinceEpoch(
                      rawData['c_created_at'],
                    )
                    : now,
            updatedAt:
                rawData['c_updated_at'] != null
                    ? DateTime.fromMillisecondsSinceEpoch(
                      rawData['c_updated_at'],
                    )
                    : now,
          );

          // 构建CeramicStage对象
          final stage = CeramicStage(
            id: rawData['stage_id'],
            ceramicId: rawData['ceramic_id'],
            type: CeramicStageType.values[rawData['type'] as int],
            status: CeramicStageStatus.values[rawData['status'] as int],
            durationSeconds: rawData['duration_seconds'] ?? 0,
            startTime:
                rawData['start_time'] != null
                    ? DateTime.fromMillisecondsSinceEpoch(rawData['start_time'])
                    : null,
            endTime:
                rawData['end_time'] != null
                    ? DateTime.fromMillisecondsSinceEpoch(rawData['end_time'])
                    : null,
            createdAt:
                rawData['cs_created_at'] != null
                    ? DateTime.fromMillisecondsSinceEpoch(
                      rawData['cs_created_at'],
                    )
                    : now,
            updatedAt:
                rawData['cs_updated_at'] != null
                    ? DateTime.fromMillisecondsSinceEpoch(
                      rawData['cs_updated_at'],
                    )
                    : now,
          );

          // 缓存用户信息
          if (!userCache.containsKey(user.id)) {
            userCache[user.id!] = user;
          }

          // 添加到去重Map中
          uniqueUserMap[userId] = {
            'user': user,
            'ceramic': ceramic,
            'stage': stage,
            'time': stage.startTime ?? DateTime.now(),
          };
        } catch (e) {
          print('处理单条烧制计时数据失败: $e');
        }
      }

      // 将去重后的Map转换为列表
      final List<Map<String, dynamic>> timerUsersList =
          uniqueUserMap.values.toList();

      // 按时间排序
      timerUsersList.sort(
        (a, b) => (b['time'] as DateTime).compareTo(a['time'] as DateTime),
      );

      // 更新状态
      timerUsers.value = timerUsersList;
    } catch (e) {
      print('加载烧制计时用户数据失败: $e');
    }
  }

  // 加载官方内容数据
  Future<void> loadOfficialContents() async {
    try {
      final contentList =
          await _officialContentRepository.getAllOfficialContents();

      if (contentList.isEmpty) {
        officialContents.value = contentList;
      } else {
        officialContents.value = contentList;
      }
    } catch (e) {
      print('加载官方内容数据失败: $e');
    }
  }

  // 预加载用户头像图片，避免滑动时闪烁
  Future<void> preloadUserImages() async {
    try {
      // 预加载所有头像图片
      final Set<String> avatarPaths = {};

      // 收集所有不同的头像路径
      for (var userData in timerUsers) {
        final user = userData['user'] as User;
        if (user.avatar != null) {
          avatarPaths.add(user.avatar!);
        }
      }

      // 添加默认头像
      avatarPaths.add(Images.avatar1);

      // 预加载所有头像
      for (var path in avatarPaths) {
        await precacheImage(AssetImage(path), Get.context!);
      }

      imagesPreloaded.value = true;
    } catch (e) {
      print('预加载图片失败: $e');
    }
  }

  // 获取用户信息
  User? getUserById(int userId) {
    return userCache[userId];
  }

  // 获取烧制阶段名称
  String getStageName(CeramicStageType type) {
    switch (type) {
      case CeramicStageType.stage1:
        return '第一阶段';
      case CeramicStageType.stage2:
        return '第二阶段';
      case CeramicStageType.stage3:
        return '第三阶段';
      case CeramicStageType.stage4:
        return '第四阶段';
      case CeramicStageType.stage5:
        return '第五阶段';
      case CeramicStageType.stage6:
        return '第六阶段';
    }
  }

  // 切换到特定页面
  void changePage(int index) {
    if (index >= 0 && index < ceramics.length) {
      currentIndex.value = index;
      pageController.animateToPage(
        index,
        duration: const Duration(milliseconds: 300),
        curve: Curves.easeInOut,
      );
      update(["home"]);
    }
  }

  // 下一个
  void nextPage() {
    if (currentIndex.value < ceramics.length - 1) {
      changePage(currentIndex.value + 1);
    }
  }

  // 上一个
  void previousPage() {
    if (currentIndex.value > 0) {
      changePage(currentIndex.value - 1);
    }
  }

  void startAutoSwipe() {
    isAutoSwiping.value = true;

    stopAutoSwipe();

    // 创建新的定时器，每5秒自动滑动一次
    _autoSwipeTimer = Timer.periodic(const Duration(seconds: 5), (timer) {
      if (isAutoSwiping.value && timerUsers.length > 1) {
        List<CardSwiperDirection> directions = [
          CardSwiperDirection.left,
          CardSwiperDirection.right,
        ];
        final randomDirection = directions[Random().nextInt(directions.length)];

        cardSwiperController.swipe(randomDirection);
      }
    });
  }

  // 停止自动滑动
  void stopAutoSwipe() {
    _autoSwipeTimer?.cancel();
    _autoSwipeTimer = null;
  }

  @override
  void onInit() {
    super.onInit();
    pageController = PageController(initialPage: 0, viewportFraction: 1.0);
    cardSwiperController = CardSwiperController();
    _initData();

    // 注册为观察者，接收陶瓷交互状态更新
    CeramicInteractionRepository.addObserver(this);
    OfficialContentRepository.addObserver(this);
    CeramicRepository.addObserver(this);
  }

  @override
  void onReady() {
    super.onReady();
    _initData();
    startAutoSwipe();
  }

  @override
  void onClose() {
    stopAutoSwipe();
    pageController.dispose();
    cardSwiperController.dispose();
    // 取消注册观察者
    CeramicInteractionRepository.removeObserver(this);
    OfficialContentRepository.removeObserver(this);
    CeramicRepository.removeObserver(this);
    super.onClose();
  }

  // 开始卡片滑动
  void startCardSwipe() {
    isCardSwiping.value = true;
  }

  // 取消卡片滑动
  void cancelCardSwipe() {
    isCardSwiping.value = false;
    cardSwipeProgress.value = 0.0;
  }

  // 更新卡片滑动进度
  void updateCardSwipeProgress(double progress) {
    cardSwipeProgress.value = progress;
  }

  // 完成卡片滑动，切换到下一个卡片
  void completeCardSwipe() {
    // 不再修改用户列表顺序，让CardSwiper自己处理显示逻辑

    // 只需处理滑动状态
    cancelCardSwipe();
    update(["home", "user_cards"]);
  }

  // 获取当前显示的陶瓷作品
  Ceramic? get currentCeramic {
    if (ceramics.isEmpty || currentIndex.value >= ceramics.length) {
      return null;
    }
    return ceramics[currentIndex.value];
  }

  // 获取当前陶瓷作品的创建者
  User? get currentCeramicUser {
    final ceramic = currentCeramic;
    if (ceramic == null) return null;
    return getUserById(ceramic.userId);
  }

  // 检查交互状态
  Future<void> checkInteractionStatus(int userId) async {
    final ceramic = currentCeramic;
    if (ceramic == null || ceramic.id == null) return;

    // 检查是否已点赞
    isCurrentCeramicLiked.value = await _interactionRepository.hasLiked(
      userId,
      ceramic.id!,
    );

    // 检查是否已收藏
    isCurrentCeramicFavorited.value = await _interactionRepository.hasFavorited(
      userId,
      ceramic.id!,
    );

    // 检查是否已关注用户
    final creatorUser = currentCeramicUser;
    if (creatorUser != null && creatorUser.id != null) {
      isCurrentUserFollowed.value = await _userFollowRepository.isFollowing(
        userId,
        creatorUser.id!,
      );
    }
  }

  // 点赞陶瓷作品
  Future<bool> toggleLikeCeramic(int userId) async {
    final ceramic = currentCeramic;
    if (ceramic == null || ceramic.id == null) return false;

    final int index = currentIndex.value;

    if (isCurrentCeramicLiked.value) {
      // 取消点赞
      final result = await _interactionRepository.unlikeCeramic(
        userId,
        ceramic.id!,
      );
      if (result) {
        isCurrentCeramicLiked.value = false;
        // 更新计数并替换列表中的对象
        ceramics[index] = ceramic.copyWith(likeCount: ceramic.likeCount - 1);
        update(["home"]);
      }
      return result;
    } else {
      // 点赞
      final result = await _interactionRepository.likeCeramic(
        userId,
        ceramic.id!,
      );
      if (result) {
        isCurrentCeramicLiked.value = true;
        // 更新计数并替换列表中的对象
        ceramics[index] = ceramic.copyWith(likeCount: ceramic.likeCount + 1);
        update(["home"]);
      }
      return result;
    }
  }

  // 收藏陶瓷作品
  Future<bool> toggleFavoriteCeramic(int userId) async {
    final ceramic = currentCeramic;
    if (ceramic == null || ceramic.id == null) return false;

    final int index = currentIndex.value;

    if (isCurrentCeramicFavorited.value) {
      // 取消收藏
      final result = await _interactionRepository.unfavoriteCeramic(
        userId,
        ceramic.id!,
      );
      if (result) {
        isCurrentCeramicFavorited.value = false;
        // 更新计数并替换列表中的对象
        ceramics[index] = ceramic.copyWith(
          favoriteCount: ceramic.favoriteCount - 1,
        );
        update(["home"]);
      }
      return result;
    } else {
      // 收藏
      final result = await _interactionRepository.favoriteCeramic(
        userId,
        ceramic.id!,
      );
      if (result) {
        isCurrentCeramicFavorited.value = true;
        // 更新计数并替换列表中的对象
        ceramics[index] = ceramic.copyWith(
          favoriteCount: ceramic.favoriteCount + 1,
        );
        update(["home"]);
      }
      return result;
    }
  }

  // 关注/取消关注用户
  Future<bool> toggleFollowUser(int followerId, int followingId) async {
    if (isCurrentUserFollowed.value) {
      // 取消关注
      final result = await _userFollowRepository.unfollowUser(
        followerId: followerId,
        followingId: followingId,
      );
      if (result) {
        isCurrentUserFollowed.value = false;
        update(["home"]);
      }
      return result;
    } else {
      // 关注
      final follow = await _userFollowRepository.followUser(
        followerId: followerId,
        followingId: followingId,
      );
      if (follow != null) {
        isCurrentUserFollowed.value = true;
        update(["home"]);
        return true;
      }
      return false;
    }
  }

  // 在页面切换时更新交互状态
  void updateInteractionStatus(int userId) {
    checkInteractionStatus(userId);
  }

  // 实现CeramicInteractionObserver接口
  @override
  void onLikeStatusChanged(int userId, int ceramicId, bool isLiked) {
    // 如果当前陶瓷与状态变更的陶瓷是同一个，则更新状态
    final UserService userService = Get.find<UserService>();
    if (userService.currentUser.value?.id == userId &&
        currentCeramic?.id == ceramicId) {
      isCurrentCeramicLiked.value = isLiked;

      // 更新列表中的点赞计数
      final int index = currentIndex.value;
      if (index >= 0 && index < ceramics.length) {
        final ceramic = ceramics[index];
        if (ceramic.id == ceramicId) {
          ceramics[index] = ceramic.copyWith(
            likeCount: isLiked ? ceramic.likeCount + 1 : ceramic.likeCount - 1,
          );
        }
      }
      update(["home"]);
    }
  }

  @override
  void onFavoriteStatusChanged(int userId, int ceramicId, bool isFavorited) {
    // 如果当前陶瓷与状态变更的陶瓷是同一个，则更新状态
    final UserService userService = Get.find<UserService>();
    if (userService.currentUser.value?.id == userId &&
        currentCeramic?.id == ceramicId) {
      isCurrentCeramicFavorited.value = isFavorited;

      // 更新列表中的收藏计数
      final int index = currentIndex.value;
      if (index >= 0 && index < ceramics.length) {
        final ceramic = ceramics[index];
        if (ceramic.id == ceramicId) {
          ceramics[index] = ceramic.copyWith(
            favoriteCount:
                isFavorited
                    ? ceramic.favoriteCount + 1
                    : ceramic.favoriteCount - 1,
          );
        }
      }
      update(["home"]);
    }
  }

  // 实现OfficialContentDeleteObserver接口
  @override
  void onOfficialContentDeleted(int contentId) {
    // 从官方内容列表中移除被删除的内容
    officialContents.removeWhere((content) => content.id == contentId);
    update(["home"]);
  }

  // 实现CeramicDeleteObserver接口
  @override
  void onCeramicDeleted(int ceramicId) {
    // 从陶瓷作品列表中移除被删除的作品
    ceramics.removeWhere((ceramic) => ceramic.id == ceramicId);
    update(["home"]);
  }
}
